#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:do_exam1.py
# author:王雯雯
# datetime:2024-11-12 
# software: PyCharm
import time
import multiprocessing


def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True


def count_primes_without_multiprocessing():
    start_time = time.time()
    prime_count = 0
    for num in range(1, 100001):
        if is_prime(num):
            prime_count += 1
    end_time = time.time()
    print(f"不使用多进程，素数个数为: {prime_count}，耗时: {end_time - start_time}秒")
    return prime_count


def count_primes_with_multiprocessing(process_num):
    start_time = time.time()
    numbers = list(range(1, 100001))
    pool = multiprocessing.Pool(processes=process_num)
    results = pool.map(is_prime, numbers)
    prime_count = sum(results)
    end_time = time.time()
    print(f"使用 {process_num} 个多进程，素数个数为: {prime_count}，耗时: {end_time - start_time}秒")
    return prime_count


if __name__ == "__main__":
    # 对比单进程和多进程（以4个进程为例）
    prime_count_without = count_primes_without_multiprocessing()
    count_primes_with_multiprocessing(4)

    # 对比不同数量多进程（4个进程和10个进程）
    count_primes_with_multiprocessing(4)
    count_primes_with_multiprocessing(10)